<?php

require_once 'Framework/Controller/Action.php';
require_once 'application/models/Room.php';
require_once 'application/models/User/Guest.php';
require_once 'application/models/User/Self.php';

class RoomController extends Framework_Controller_Action
{
	private $_room;
	private $_chatId;
	
    public function init()
    {
		$this->view->adminnum = $this->session->get('adminnum');
		$this->view->current_page="chat";
		if (!$this->session->get('authorize'))	{
			$this->_redirect('/admin/');
		}
    }
    
    public function indexAction()
    {
    	$this->_chatId = $this->_getParam(0,'');
    	if ($this->session->get('logged_in'.$this->_chatId)) {
			$this->view->rooms = Room::getRooms();
			$this->view->username = $this->session->get('user_login' . 
															$this->_chatId);
	        $this->render();	
		} else {
			$this->_redirect('/admin/chat/');	
		}
    }
	
	public function chatAction()
	{
		$this->_chatId = $this->_getParam(1,''); //wtf?
		
		$this->_room = new Room(get_value($this->_getParam(0)));
		$this->_room->isUserAccess('user_id'.$this->_chatId);
		
		$user = new User_Self($this->session->get('user_id'.$this->_chatId));
		$this->_room->addUser($user);
		
		$this->view->messages = $this->_room->getRoomMessages(20);
		$this->view->online_users = $this->_room->getUsersOnline();
		$this->view->room_name = $this->_room->room_name;
		$this->view->room_id = $this->_room->room_id;
		$this->session->set('admin_room_id',$this->_room->room_id);
		unset($this->_room);
		$this->render();
	} 
	
	public function writeAction()
	{
		if ($this->getRequest()->getMethod() == 'POST')	{
			$this->_chatId = $this->_getParam(1,'');
			$room_id = $this->session->get('admin_room_id');
			$message = get_value($this->getRequest()->getParam('message'));
			$this->_room = new Room($room_id);
			$this->_room->isUserAccess('user_id'.$this->_chatId);
			$this->_room->addMessage($this->session->get('user_id' . 
														$this->_chatId), $message);
			unset($this->_room);
			$this->_redirect('/admin/room/chat/'.$room_id);
		}
		$this->view->room_id = get_value($this->_getParam(0));
		$this->render();
	}
	
}
